package org.lztvn.elearning.controllers;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.commons.io.IOUtils;
import org.lztvn.elearning.entities.News;
import org.lztvn.elearning.service.INewsService;
import org.lztvn.elearning.service.Utility;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

@Controller
@SessionAttributes("editedNews")
public class NewsController extends AppController{
	@Autowired
	INewsService service;
	
	Utility util;

	private void init() {
		ApplicationContext context = new ClassPathXmlApplicationContext(
				"applicationContext.xml");
		this.util = (Utility) context.getBean("util");
	}
	
	
	@RequestMapping(value = "/news", method = RequestMethod.GET)
	public ModelAndView index(Model model, HttpSession session) {
		init();
		if (util.checkSession(session) == false) {
			return new ModelAndView("redirect:login");
		} else {
			model.addAttribute("news", new News());
			model.addAttribute("list_news", service.listNews());
			return new ModelAndView("news");
		}

	}
	
	@RequestMapping(value = "/saveNews", method = RequestMethod.POST)
	public String saveCon(@Valid News n, BindingResult bindingResult,
			Model model, MultipartFile file) throws IOException {
		if (bindingResult.hasErrors()) {
			model.addAttribute("list_news", service.listNews());
			return ("news");
		}

		if (!file.isEmpty()) {
			BufferedImage bi = ImageIO.read(file.getInputStream());
			n.setPhoto(file.getBytes());
			n.setNomPhoto(file.getOriginalFilename());
		}
		if (n.getId() != null) {
			if (model.asMap().get("editedNews") != null) {
				if (file.isEmpty()) {
					News us = (News) model.asMap().get("editedNews");
					n.setPhoto(us.getPhoto());
				}
			}
			service.modifierNews(n);
		} else
			service.addNews(n);

		model.addAttribute("news", new News());
		model.addAttribute("list_news", service.listNews());
		return "news";
	}
	
	
	@RequestMapping(value = "photoNews", produces = MediaType.IMAGE_JPEG_VALUE)
	@ResponseBody
	public byte[] photoNews(Long id) throws IOException {
		News n = service.getNews(id);
		return IOUtils.toByteArray(new ByteArrayInputStream(n.getPhoto()));
	}

	@RequestMapping(value = "/delNews")
	public ModelAndView delNews(Long id, Model model, HttpSession session) {
		init();
		if (util.checkSession(session) == false) {
			return new ModelAndView("redirect:login");
		} else {
			service.deleteNews(id);
			model.addAttribute("news", new News());
			model.addAttribute("list_news", service.listNews());
			return new ModelAndView("news");
		}
	}

	
	
	@RequestMapping(value = "/editNews")
	public ModelAndView editNews(Long id, Model model, HttpSession session) {
		init();
		if (util.checkSession(session) == false) {
			return new ModelAndView("redirect:login");
		} else {
			News n = service.getNews(id);
			model.addAttribute("editedNews", n);
			model.addAttribute("news", n);
			model.addAttribute("list_news", service.listNews());
			return new ModelAndView("news");
		}
	}

	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object arg2, Exception ex) {
		ModelAndView mv = new ModelAndView();
		mv.addObject("news", new News());
		mv.addObject("list_news", service.listNews());
		mv.addObject("exception", ex.getMessage());
		mv.setViewName("news");
		return mv;
	}
}
